import {
    createApp,
    nextTick
} from 'vue'
import GLOBAL from './global'
import poiLayer from '@/view/poiLayer/main'
import {
    pointProp
} from "@/utils/pointProp";

/*
 *点的经纬度，圆心的经纬度
 */
let latreg = /^(\-|\+)?([0-8]?\d{1}\.\d{0,15}|90\.0{0,15}|[0-8]?\d{1}|90)$/;
let longrg = /^(\-|\+)?(((\d|[1-9]\d|1[0-7]\d|0{1,3})\.\d{0,15})|(\d|[1-9]\d|1[0-7]\d|0{1,3})|180\.0{0,15}|180)$/;

export function showAttribute() {
    //点击显示属性
    let editHandler = new Cesium.ScreenSpaceEventHandler(
        sgworld.Viewer.scene.canvas
    );
    editHandler.setInputAction((event) => {
        //兼容地下模式
        if (
            Cesium.ExpandBySmartEarth &&
            (Cesium.ExpandBySmartEarth.underEarth.enable ||
                Cesium.ExpandBySmartEarth.isStreetView)
        ) {
            return;
        }
        // 获取屏幕坐标
        let windowPosition = event.position;
        // 通过屏幕坐标获取当前位置的实体
        let pickedObject = sgworld.Viewer.scene.pick(windowPosition);

        var earthPosition = sgworld.Viewer.camera.pickEllipsoid(
            event.position,
            sgworld.Viewer.scene.globe.ellipsoid
        );
        var cartographic = Cesium.Cartographic.fromCartesian(
            earthPosition,
            sgworld.Viewer.scene.globe.ellipsoid,
            new Cesium.Cartographic()
        );

        console.log(
            `lat:${Cesium.Math.toDegrees(
                cartographic.latitude
            )},lng:${Cesium.Math.toDegrees(cartographic.longitude)}`
        );



        //处理POI点位弹窗
        if (
            pickedObject &&
            pickedObject.id &&
            pickedObject.id._description &&
            pickedObject.id._description._value &&
            pickedObject.id._description._value.write
        ) {
            closePoiLayer();
            if (window.poiEntity) {
                window.poiEntity.billboard.scale._value = 0.6;
            }
            window.poiEntity = pickedObject.id;
            pickedObject.id.billboard.scale._value = 0.8;
            creatPoiLayer(pickedObject.id._description._value,
                [pickedObject.id._description._value.x, pickedObject.id._description._value.y],
                pickedObject.id
            )

        }

    }, Cesium.ScreenSpaceEventType.LEFT_CLICK);

}

export function closePoiLayer() {

    if (GLOBAL.poiLayerObj) {
        GLOBAL.poiLayerObj.deleteObject()
    }

    if (window.poiEntity) {
        window.poiEntity.billboard.scale._value = 0.8;
    }

    //销毁之前的弹窗组件
    if (GLOBAL.instance) {
        GLOBAL.instance.unmount()
    }
}



/**
 * 图层树勾选撒点时，操作其他功能，点位不删除，做特殊处理
 * @param {*} attr 
 * @param {*} name 
 * @returns 
 */
export function createPoi(attr, name = '') {

    if (!attr.x || !attr.y) return;

    if (!longrg.test(attr.x) || !latreg.test(attr.y)) return;

    var position = sgworld.Creator.CreatePosition(attr.x, attr.y, 0);

    var _obj = sgworld.Creator.CreateLabel(position, name, SmartEarthRootUrl + attr.icon, {
        // 文本偏移量
        pixelOffset: {
            x: 0,
            y: 20
        },
        IconColor: '#FFFFFF',
        BackgroundColor: Cesium.Color.fromCssColorString("#409EFF"),
        showBackground: true,
        Bold: true,
        Scale: 1,
        ImageScale: attr.scale || 0.8,
        font: '13px Phetsarath',

        distanceDisplayCondition: new Cesium.DistanceDisplayCondition(0, window.POITEXT_MAXHEIGHT)
    }, 0, "");

    _obj.item.description = attr;

    GLOBAL.poiContainer[attr.type].push(_obj.item.id);


    return _obj.item.id
}

//删除POI
export function delPoi(type) {
    if (GLOBAL.poiContainer[type]) {
        GLOBAL.poiContainer[type].forEach(function (obj) {
            let entity = sgworld.Viewer.entities.getById(obj);
            sgworld.Viewer.entities.remove(entity);
        });
        GLOBAL.poiContainer[type] = null
    }
}


//针对飞到POI点弹窗部分被遮挡问题进行视角偏移处理(只做纵向偏移)
export function flyToPoiShift(lng, lat, height, offset = window.POIVIEWOFFSET) {
    const offsetToLat = Number(((offset / (18395.875 / height)) * 0.0001).toFixed(8))

    lng = Number(lng);
    lat = Number(lat);

    sgworld.Navigate.flyToPosition(lng, lat + offsetToLat, height, {
        time: 1.2
    });
}

//创建POI的跟随弹窗
/**
 * 
 * @param {*} write 弹窗需要展示的内容
 * @param {*} local 当前位置坐标[lng,lat]
 * @param {*} cartesian3 cartesian3坐标
 * @param {*} pid POI的ID
 * @param {*} isFlyto 是否飞到定位点
 */
let timeOut = null;
export async function creatPoiLayer(write, local, entity, isFlyto = true) {

    let _data = {
        list: write
    }

    GLOBAL.instance = createApp(poiLayer, _data);
    GLOBAL.poiLayerObj = sgworld.Creator.createDivPoint('', {
        lon: local[0],
        lat: local[1]
    }, {
        id: 'POI',
        type: "custom",
        offset: ["c", 60],
        description: '',
        near: 0,
        far: 8000000
    });

    if (timeOut) {
        clearTimeout(timeOut);
    }

    timeOut = setTimeout(() => {
        GLOBAL.instance.mount('#POI .divpoint');
        timeOut = null;
    }, 500)

    if (isFlyto) {
        const cartesian3 = Cesium.Cartesian3.fromDegrees(local[0], local[1], 10);
        let distance = sgworld.Core.getPointToCameraDistance(Viewer, cartesian3);
        flyToPoiShift(local[0], local[1], distance)
    }
}


//绘制视频覆盖范围
export function drawVideoRange(posi = []) {
    let geometry = [];
    posi.forEach(item => {
        geometry.push({
            x: item.longitude,
            y: item.latitude,
            z: 10
        })
    });
    GLOBAL.VIDEORANGE = sgworld.Creator.createPolygon(geometry, {
        fillColor: '#00ff0050',
        outlineColor: '#ff0000',
        outlineWidth: 2
    }, 1, 0, "面");
}